package cn.rui.security;

import cn.rui.common.Result;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 浏览器环境下登录成功的处理器
 *
 * @author yuyi
 * @version 1.0
 */
@Slf4j
@Component
public class BrowserAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {


	//private RequestCache requestCache = new HttpSessionRequestCache();

	/**
	 * (non-Javadoc)
	 *
	 * @see org.springframework.security.web.authentication.AuthenticationSuccessHandler#onAuthenticationSuccess(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, Authentication)
	 */
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {

		//log.info("login successful");

		response.setHeader("Content-type", "text/html;charset=UTF-8");
		String jsonString = JSON.toJSONString (Result.getSuccess ("登录成功!"));

		PrintWriter writer = response.getWriter ();
		writer.append (jsonString);
		writer.flush ();

//		setAlwaysUseDefaultTargetUrl(true);
	//	setDefaultTargetUrl ("/index.html");
		//super.onAuthenticationSuccess(request, response, authentication);
		//response.sendRedirect (request.getContextPath ()+"/index");
	}

}
